package com.fund;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.okhttp.OKHttpUtil;

import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;

public class FundSelect {

    public final static List<String[]> db = new ArrayList<>(); 
    
	public static void main(String[] args) {
		selectFund();
	}

	public static void selectFund() {
	    db.clear();
		String ft = "hh"; // 混合型
		String y = "3n"; // 近三年
		String top = "100"; // 排名前100
		String size = "100"; // 分页大小
		String url = "http://fund.eastmoney.com/data/FundGuideapi.aspx?dt=0&ft=" + ft + "&rs=" + y + "," + top
				+ "&sd=&ed=&sc=3n&st=desc&pi=1&pn=" + size + "&zf=diy&sh=list&rnd=0.7558709930361405";
		String fundStr = OKHttpUtil.get(url);
		analysisData(fundStr.replace("var rankData =", ""));

	}

	// 解析筛选的基金数据
	static void analysisData(String str) {
		JSONObject root = JSONObject.parseObject(str);
		JSONArray funds = root.getJSONArray("datas");
		log("共" + funds.size() + "只");
		log("基金号\t一周\t一月\t三月\t六月\t今年以来\t近1年\t近2年\t近三年\t近一年定投500收益\t基金规模\t单位净值\t名称");
		// log("基金号\t7\t30\t90\t180\t60\t360\t720\t1080\t基金规模\t单位净值\t名称");
		
		StringBuilder sbcsv = new StringBuilder();
		sbcsv.append("基金号,一周,一月,三月,六月,今年以来,近1年,近2年,近三年,近一年定投500收益,基金规模,单位净值,名称\n");
		
        StringBuilder sb = new StringBuilder();
		int selected = 0;
		int index = 0;
		for (Object object : funds) {
			String rowStr = (String) object;
			String[] fd = rowStr.split(",");
			String fundCode = fd[0];
			Document doc = null;
			try {
				doc = Jsoup.connect("http://fund.eastmoney.com/" + fundCode + ".html").get();
			} catch (IOException e) {
				e.printStackTrace();
			}
			String[] states = parseHtml(doc);

			// 三个月以后的数据都是优秀和良好
			boolean good = isGood(states);
			String total = parseFundTotal(doc);
			double fundTotal = Double.parseDouble(total);

			if (fundTotal > 3.0 // 规模大于3亿
					&& good && Double.parseDouble(fd[7]) > -3 // 近3个月收益
					&& Double.parseDouble(fd[8]) > 0 // 近6个月
					&& Double.parseDouble(fd[4]) > 0 // 今年
					&& Double.parseDouble(fd[9]) > 0 // 近1年
					&& Double.parseDouble(fd[10]) > 0 // 近2年
					&& Double.parseDouble(fd[11]) > 0 // 近3年
			) {

				selected++;

				log(fd[0]

						+ "\t" + formatPecent(fd[5]) + states[0].substring(0, 1) // 近1周
						+ "\t" + formatPecent(fd[6]) + states[1].substring(0, 1) // 近1月
						+ "\t" + formatPecent(fd[7]) + states[2].substring(0, 1) // 近3月
						+ "\t" + formatPecent(fd[8]) + states[3].substring(0, 1) // 近6月
						+ "\t" + formatPecent(fd[4]) + states[4].substring(0, 1) // 今年以来
						+ "\t" + formatPecent(fd[9]) + states[5].substring(0, 1) // 近1年
						+ "\t" + formatPecent(fd[10]) + states[6].substring(0, 1) // 近2年
						+ "\t" + formatPecent(fd[11]) + states[7].substring(0, 1) // 近3年
						+ "\t" + getFixPut500percnt(fundCode)

						+ "\t" + total + "\t" + fd[16] + "\t" + fd[1]);
				
				
				    sbcsv.append(fd[0]
				    +"," + formatPecent(fd[5]) + states[0].substring(0, 1) 
				    +"," + formatPecent(fd[6]) + states[1].substring(0, 1) 
				    +"," + formatPecent(fd[7]) + states[2].substring(0, 1) 
				    +"," + formatPecent(fd[8]) + states[3].substring(0, 1) 
				    +"," + formatPecent(fd[4]) + states[4].substring(0, 1) 
				    +"," + formatPecent(fd[9]) + states[5].substring(0, 1) 
				    +"," + formatPecent(fd[10]) + states[6].substring(0, 1) 
				    +"," + formatPecent(fd[11]) + states[7].substring(0, 1) 
				    +"," + getFixPut500percnt(fundCode)
				    +"," + total + "," + fd[16] + "," + fd[1]+"\n");
				// String fundStr =
				// OKHttpUtil.get("http://fund.eastmoney.com/pingzhongdata/"+fd[0]+".js");
				// String jsData=getData(fundStr);
				// sb.append("var xxff"+index+"="+jsData+"\n");
				   
				  db.add(new String[] {
				        fd[0],
				        total,
				        fd[16],
				        fd[1],
				        formatPecent(fd[5]) + states[0], 
	                    formatPecent(fd[6]) + states[1],
	                    formatPecent(fd[7]) + states[2], 
	                    formatPecent(fd[8]) + states[3], 
	                    formatPecent(fd[4]) + states[4], 
	                    formatPecent(fd[9]) + states[5], 
	                    formatPecent(fd[10]) + states[6], 
	                    formatPecent(fd[11]) + states[7], 
	                    getFixPut500percnt(fundCode)
				    });
				index++;
				// break;
			}
		}
		
		
		Collections.sort(db, new Comparator<String[]>() {

            @Override
            public int compare(String[] o1, String[] o2) {
                 return (int)(Double.parseDouble(o2[1])-Double.parseDouble(o1[1]));
        }});
//      写html
//		sb.append("var xxData =[];\n");
//		for (int i = 0; i < index; i++) {
//			sb.append("xxData.push(xxff"+i+");\n");
//		}
//		String htmlStr = FileUtil.readTxtFile("template/index.html").toString();
//		htmlStr = htmlStr.replace("#xxData#", sb.toString());
//		FileUtil.writeTxtFile(htmlStr, "data/index.html");
		//FileUtil.writeTxt(sbcsv.toString(), "data/index.csv");
		log("筛选出" + selected + "只");
	}

	// 四分位排名优秀
	static boolean isGood(String[] states) {
		boolean good = true;
		for (int i = 0; i < states.length; i++) {
			// 三个月以后的数据都是优秀和良好
			if (i > 0 && !states[i].equals("优秀")) {
				good = false;
				break;
			}
		}
		return good;
	}

	// 解析四分位置排名
	static String[] parseHtml(Document doc) {
		String[] states = new String[8];
		Elements elements = doc.select("#increaseAmount_stage .ui-table-hover h3");
		int i = 0;
		for (Element element : elements) {
			states[i] = element.text();
			i++;
		}
		return states;
	}

	// 解析基金规模
	static String parseFundTotal(Document doc) {
		Element element = doc.select(".infoOfFund table td:eq(1)").get(0);
		String total = element.text();
		total = total.substring(total.indexOf("：")+1);
		total = total.substring(0, total.indexOf("亿"));
		return total.trim();
	}

	// 获取近6个月收益数据
	static String getData(String str) {
		String start = "var Data_grandTotal =";
		String end = "同类排名走势";
		int s = str.indexOf(start);
		int e = str.indexOf(end);
		if (s > 0 && e > 0)
			return str.substring(s + start.length(), e - 2);
		return "";
	}

	static String getFixPut500percnt(String code) {
		
		 RequestBody formBody = new FormBody.Builder()
				.add("fundCode", code)
				.add("fundName", "易方达平稳增长混合 基金")
				.add("fixedAmount", "500")
				.add("startTime", "2019-04-17")
				.add("endTime", "2020-04-15")
				.add("redeemTime", "2020-04-15")
				.add("periodType", "0")
				.add("periodValue", "01")
				.add("chargeType", "0")
				.add("bonusType", "0")
				.add("frontRateRebate", "10")
				.add("calcTimeStart", System.currentTimeMillis()+"")
	             .build();
	     Request request = new Request.Builder()
	             .url("http://tools.fund.10jqka.com.cn/data/Fdcalculator/fixedCalculator")
	             .post(formBody)
	             .build();
	    try {
			String res = OKHttpUtil.client.newCall(request).execute().body().string();
			//log(res);
			String pStr = "\\u6295\\u8d44\\u6536\\u76ca\\u7387<\\/strong>\\r\\n<span class=\\\"c_hint\\\">";
			int startIndex = res.indexOf(pStr);
			return res.substring(startIndex+pStr.length(), startIndex+pStr.length()+6);
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	    
		return "";
	}
	static void log(Object o) {
		System.out.println(o);
	}

	static String formatPecent(String d) {
		return format(d) + "%";
	}

	static String format(String d) {
		if ("".equals(d))
			return null;
		return String.format("%.2f", Double.parseDouble(d));
	}

}
